package com.yu.blog.cofig.security.service.impl;

import com.yu.blog.cofig.security.mapper.AuthMapper;
import com.yu.blog.cofig.security.service.AuthUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class AuthUserDetailsServiceImpl implements AuthUserDetailsService {

    @Autowired
    private AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        HashMap<String, String> adminInfo = authMapper.getAdminInfo(username);
        if (adminInfo == null) {
            throw new UsernameNotFoundException("用户名或密码不正确");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(adminInfo.get("role_code")));
        return User.withUsername(adminInfo.get("admin_name"))
                .password(adminInfo.get("admin_password"))
                .authorities(authorities)
                .build();
    }
}
